package com.example.clock;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ListView monthListView;
    private ListView dataListView;

    private MonthListViewAdapter monthListViewAdapter;
    private List<String> month;
    private DataListViewAdapter dataListViewAdapter;
    private List<DataInfoBean> dataInfoBeans;

    private MySQLite mySQLite;
    private SharedPreferences preferences;

    //default Year is 2021
    private static String defaultYear;

    private static int defaultMonth = 1;
    private static int year;
    private static int monthIndex = 1;
    private static int countOfMonth = 0;
    private static int timeCountOfMonth = 0;
//    private static int moneyOfMonth = 0;

    static {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //拿到用户设置的年份 默认是2021
        preferences = this.getSharedPreferences(Constant.SharedPreferencesName,0);
        if (preferences.getInt(Constant.currentYear,0)!=0){
            defaultYear = "B"+preferences.getInt(Constant.currentYear,2021);
            year = preferences.getInt(Constant.currentYear,2021);
        }else{
            SharedPreferences.Editor editor = preferences.edit();
            editor.putInt(Constant.currentYear,2021);
            editor.apply();
            defaultYear = Constant.defaultTabName;
            year = 2021;
        }
        //数据库初始化
        mySQLite = new MySQLite(MainActivity.this,defaultYear,null,1);

        init();
        initEvent();
    }

    private void init() {
        //拿到控件
        monthListView = (ListView) findViewById(R.id.Month_List);
        dataListView = (ListView) findViewById(R.id.Data_List);
        //月份容器
        month = new ArrayList<>();
        //拿到月份数据
        getMonth();
        //月份适配器
        monthListViewAdapter = new MonthListViewAdapter(MainActivity.this,month);
        //月份ListView设置适配器
        monthListView.setAdapter(monthListViewAdapter);

        //数据库实际数据
        dataInfoBeans = new ArrayList<>();
        //实际数据列表适配器
        dataListViewAdapter = new DataListViewAdapter(MainActivity.this,dataInfoBeans);
        //数据列表监听
        dataListViewAdapter.setListener(new DataListViewAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClicked(int year, int month, int day) { //长按事件
                LongClickDialog dialog = new LongClickDialog(MainActivity.this);
                dialog.setListener(new LongClickDialog.onItemSelectedListener() {
                    @Override
                    public void onChangeData() { //修改数据
                        AddDataDialog addDatadialog = new AddDataDialog(MainActivity.this);
                        addDatadialog.setListener(new AddDataDialog.OnButtonClickListener() {
                            @Override
                            public void onOkClicked(String department, int workTime) {
                                if (changData(department,workTime,year,month,day)){
                                    Toast.makeText(MainActivity.this,"已修改",Toast.LENGTH_LONG).show();
                                    addDatadialog.dismiss();
                                    dialog.dismiss();
                                    getSqlWorkData(year,month);
                                }else{
                                    addDatadialog.dismiss();
                                    dialog.dismiss();
                                    Toast.makeText(MainActivity.this,"修改失败",Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                        addDatadialog.show();
                    }

                    @Override
                    public void onDeleteData() { //删除数据
                        TipsDialog tipsDialog = new TipsDialog(MainActivity.this);
                        tipsDialog.setListener(new TipsDialog.OnItemClickListener() {
                            @Override
                            public void onPositionClicked() {
                                deleteData(year,month,day);
                                getSqlWorkData(year,month);
                                tipsDialog.dismiss();
                                dialog.dismiss();
                            }
                        });
                        tipsDialog.show();
                    }
                });
                dialog.show();
            }
        });
        getSqlWorkData(year,defaultMonth);
        dataListView.setAdapter(dataListViewAdapter);
    }

    private void initEvent() {
        monthListView.setSelector(R.color.brown);
        monthListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //当前月份
                monthIndex = position+1;
//                for (int i = 0 ; i < 13 ; i++){
//                    ((View) monthListView.getAdapter().getItem(position)).setBackground(getDrawable(R.drawable.month_comm));
//                }
//                view.setBackground(getResources().getDrawable(R.drawable.month_selected));
//                for(int i=0;i<parent.getCount();i++){
//                    View v=parent.getChildAt(position);
//                    if (position != i) {
//                        v.setBackground(getDrawable(R.drawable.month_comm));
//                    } else {
//                        v.setBackground(getDrawable(R.drawable.month_selected));
//                    }
//                }
                //重置时间总和
                timeCountOfMonth = 0;
                getSqlWorkData(year,monthIndex);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.add:
                AddDataDialog dialog = new AddDataDialog(MainActivity.this);
                dialog.setListener(new AddDataDialog.OnButtonClickListener() {
                    @Override
                    public void onOkClicked(String department, int workTime) {
                        if (writeData(department,workTime)){
                            Toast.makeText(MainActivity.this,"添加成功",Toast.LENGTH_LONG).show();
                        }else{
//                            Toast.makeText(MainActivity.this,"程序有误",Toast.LENGTH_LONG).show();
                        }
                        dialog.dismiss();
                        getSqlWorkData(year,monthIndex);
                    }
                });
                dialog.show();
                break;
            case R.id.addPointer:
                AddPointDataDialog dataDialog = new AddPointDataDialog(MainActivity.this);
                dataDialog.setListener(new AddPointDataDialog.OnButtonClickListener() {
                    @Override
                    public void onOkClicked(String department, int workTime, String date) {
                        if (writeData(department,workTime,date)){
                            Toast.makeText(MainActivity.this,"添加成功",Toast.LENGTH_LONG).show();
                        }
                        dataDialog.dismiss();
                    }
                });
                dataDialog.show();
                break;
            case R.id.count:
                CountDialog countDialog = new CountDialog(MainActivity.this);
                countDialog.setDate(defaultYear+"年"+monthIndex+"月");
                countDialog.setCountOfMonth(countOfMonth);
                countDialog.setTimeCountOfMonth(timeCountOfMonth);
                countDialog.show();
                break;
            case R.id.changeYear:
                ChangeYearDialog changeYearDialog = new ChangeYearDialog(MainActivity.this);
                changeYearDialog.setMainActivity(this);
                changeYearDialog.show();
                getSqlWorkData(year,monthIndex);
                break;
            case R.id.YearCount:
                startActivity(new Intent(MainActivity.this,YearCountActivity.class));
                break;
            case R.id.about:
                startActivity(new Intent(MainActivity.this,AboutActivity.class));
            default:
                break;
        }
        return true;
    }

    public void setYear(String year){
        Toast.makeText(MainActivity.this,"已经切换到"+year+"年",Toast.LENGTH_SHORT).show();
        defaultYear = "B"+year;
        this.year = Integer.parseInt(year);
        mySQLite = new MySQLite(MainActivity.this,defaultYear,null,1);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt(Constant.currentYear,this.year);
        editor.apply();
    }

    private Boolean writeData(String department, int workTime) {
        if (checkDataRepeat()){
            Toast.makeText(MainActivity.this,"今天已添加",Toast.LENGTH_LONG).show();
            return false;
        }
        SQLiteDatabase db = mySQLite.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("department",department);
        values.put("worktime",workTime);
        values.put("year",year);
        values.put("month",monthIndex);
        values.put("day", Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        long id = db.insert(defaultYear,null,values);
        if (id>0){
            return true;
        }else{
            return false;
        }
    }
    private Boolean writeData(String department, int workTime ,String date) {
        String[] d = date.split("/");
        int year = Integer.parseInt(d[0]);
        int month = Integer.parseInt(d[1]);
        int day = Integer.parseInt(d[2]);
        if (checkDataRepeat(year,month,day)){
            Toast.makeText(MainActivity.this,"指定的日期已有数据",Toast.LENGTH_LONG).show();
            return false;
        }
        SQLiteDatabase db = mySQLite.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("department",department);
        values.put("worktime",workTime);
        values.put("year",year);
        values.put("month",month);
        values.put("day", day);
        long id = db.insert(defaultYear,null,values);
        if (id>0){
            return true;
        }else{
            return false;
        }
    }

    private boolean checkDataRepeat() {
        SQLiteDatabase db = mySQLite.getReadableDatabase();
        Cursor cursor = db.query(defaultYear,null,"month = ? And day = ?",new String[]{monthIndex+"",Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+""},null,null,null);
        if (cursor.getCount() > 0){
            return true;
        }
        return false;
    }

    private boolean checkDataRepeat(int year , int month , int day) {
        SQLiteDatabase db = mySQLite.getReadableDatabase();
        Cursor cursor = null;
        try{
            cursor = db.query(defaultYear,null,"month = ? And day = ?",new String[]{month+"",day+""},null,null,null);
        }catch (Exception e){
            Toast.makeText(MainActivity.this,"大几率是指定的年份不正确",Toast.LENGTH_LONG).show();
        }
        if (cursor.getCount() > 0){
            return true;
        }
        return false;
    }


    private void deleteData(int year, int month, int day) {
        SQLiteDatabase db = mySQLite.getWritableDatabase();
        int i = db.delete(defaultYear,"month=? And day=?",new String[]{month+"",day+""});
        if(i > 0){
            Toast.makeText(MainActivity.this,"已删除",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(MainActivity.this,"删除失败",Toast.LENGTH_LONG).show();
        }
    }
    //修改数据
    private Boolean changData(String department, int workTime,int year, int month, int day) {
        SQLiteDatabase db = mySQLite.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("department",department);
        values.put("worktime",workTime);
        long result = db.update(defaultYear,values,"month=? And day=?",new String[]{month+"",day+""});
        if (result>0){
            return true;
        }else {
            return false;
        }
    }

    private void getSqlWorkData(int year,int month) {
        //清空数据源
        dataInfoBeans.clear();
        //重新访问数据库
        SQLiteDatabase db = mySQLite.getReadableDatabase();
        Cursor cursor = db.query(defaultYear,null,"`month`=?",new String[]{month+""},null,null,"day");
        countOfMonth = cursor.getCount();
        if (cursor.getCount() != 0){
//            cursor.moveToFirst();
            while (cursor.moveToNext()){
                DataInfoBean bean = new DataInfoBean();
                bean.setYear(cursor.getInt(cursor.getColumnIndex("year")));
                bean.setMonth(cursor.getInt(cursor.getColumnIndex("month")));
                bean.setDay(cursor.getInt(cursor.getColumnIndex("day")));
                bean.setDepartment(cursor.getString(cursor.getColumnIndex("department")));
                bean.setWorkTime(cursor.getInt(cursor.getColumnIndex("worktime")));
                timeCountOfMonth += bean.getWorkTime();
                dataInfoBeans.add(bean);
            }
        }
        dataListViewAdapter.setList(dataInfoBeans);
    }

    //12个月
    private void getMonth() {
        for (int i = 1 ; i < 13 ; i++){
            month.add(i+"月");
        }
    }
}